package cn.well.cloud.core.auth.entrypoint;

import cn.stylefeng.roses.core.util.RenderUtil;
import cn.stylefeng.roses.kernel.model.response.ErrorResponseData;
import cn.well.cloud.base.auth.exception.enums.AuthExceptionEnum;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.AuthenticationEntryPoint;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.Serializable;

/**
 * 用户访问受保护资源但是不提供任何token的情况下
 * 2019年12月23日
 * @author wison
 *
 */
@Component
public class JwtAuthenticationEntryPoint implements AuthenticationEntryPoint, Serializable {

    private static final long serialVersionUID = -1L;

    @Override
    public void commence(HttpServletRequest request,
                         HttpServletResponse response,
                         AuthenticationException authException) throws IOException {

        // GET请求跳转到主页
//        if ("get".equalsIgnoreCase(request.getMethod())
//                && !request.getHeader("Accept").contains("application/json")) {
//
//            response.sendRedirect(request.getContextPath() + "/global/sessionError");
//
//        } else {
//
//            // POST请求返回json
//            response.setCharacterEncoding("utf-8");
//            response.setContentType("application/json");
//
//            ErrorResponseData errorResponseData = new ErrorResponseData(
//                    AuthExceptionEnum.NOT_LOGIN_ERROR.getCode(), AuthExceptionEnum.NOT_LOGIN_ERROR.getMessage());
//
//            response.getWriter().write(JSON.toJSONString(errorResponseData));
//        }
        
        ErrorResponseData errorResponseData = new ErrorResponseData(
                AuthExceptionEnum.NOT_LOGIN_ERROR.getCode(), AuthExceptionEnum.NOT_LOGIN_ERROR.getMessage());
        RenderUtil.renderJson(response,errorResponseData);
    }
}